package com.mou.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.mou.entity.Captcha;
import com.mou.service.CaptchaService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Service("captchaService")
public class CaptchaServiceImpl implements CaptchaService {
    private final ConcurrentHashMap<String, Captcha> cache = new ConcurrentHashMap<>();

    @Override
    public String generateCode(String email) {
        String code = RandomUtil.randomNumbers(6);
        cache.put(email, new Captcha(code, LocalDateTime.now().plusMinutes(5)));
        return code;
    }

    @Override
    // 验证验证码
    public boolean validateCode(String email, String code) {
        Captcha info = cache.get(email);
        if (info == null || info.getExpireTime().isBefore(LocalDateTime.now())) {
            return false;
        }
        return info.getCode().equals(code);
    }


}
